//
//  SearchDirectoryViewController.m
//  HandyDialer
//
//	Developed by Team Synergy
//  Created by Jordan Tseng on 10/29/11.
//  Coders: Jacky Li and Jordan Tseng 
//  Graphic Designer: Derek Fong
//  Developer: Brad Lisson, Derek Fong, Jacky Li, Jeremy Gangoso, Jordan Tseng
//  Copyright HandyDialer 2011. All rights reserved.
//


#import "SearchDirectoryViewController.h"


@implementation SearchDirectoryViewController
@synthesize highlightArea;
@synthesize backgroundArea;
@synthesize reverseNumber;


 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
    {
        // Custom initialization
		rowCounter = 0;
		columnCounter = 0;
		iterationCounter = 0;
		buttonSelect = FALSE;

		
    }
    return self;
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_search_default.png"]]];
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated
{
    defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_search_default.png"]]];
	if (uniTimer == nil && buttonSelect == FALSE)
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
	else if (uniTimer == nil && buttonSelect == TRUE)
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(buttonChange) userInfo:nil repeats:YES];
	[super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	if (uniTimer != nil)
	{
			[uniTimer invalidate];
			uniTimer = nil;
	}
	[super viewDidDisappear:animated];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


- (void)viewDidUnload 
{
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	
}


- (void)dealloc 
{
	[highlightArea release];
    [super dealloc];
}

- (void)highlightChange:(NSString *)picture
{
    UIImage *image = [UIImage imageNamed: picture];
    [highlightArea setImage:image];
	
}

- (void)appendNum:(int)input
{
	NSString *charList[11] = {@"1", @"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",nil};
	if (number == NULL)
	{
		number = charList[input];
	}
	else
	{
		number = [number stringByAppendingString:charList[input]];
	}
	number = [self parseNum:number];
	[number retain];
	reverseNumber.text = number;
	NSLog(@"%@",number);
	
}

- (NSString *)parseNum:(NSString *)num
{
	// only check if it is within valid length
	if ([num length] > 5 && [num length] < 12)
	{
		// 1- cases
		if ([num hasPrefix:@"1"])
		{
			// check if all digits are 1
			if ([[num componentsSeparatedByString:@"1"] count] != [num length]+1)
			{
				
				if ([num length] == 6)
				{
					if ([num characterAtIndex:1] == '-')
					{
						num = [NSString stringWithFormat:@"%@-%@",[num substringToIndex:5],[num substringFromIndex:5]];	 
					}
					else
					{
						num = [NSString stringWithFormat:@"%@-%@-%@",[num substringWithRange:NSMakeRange(0,1)],[num substringWithRange:NSMakeRange(1,3)],[num substringFromIndex:4]];
					}
				}
				else if ([num length] == 11)
				{
					num = [NSString stringWithFormat:@"%@-%@", [num substringToIndex:9], [num substringFromIndex: 9]];
				}
			}
		}
		// no country code
		else
		{
			if ([num length] == 6)
			{
				num = [NSString stringWithFormat:@"%@-%@", [num substringToIndex:3], [num substringFromIndex:3]];
			}
			else if ([num length] == 9)
			{
				num = [NSString stringWithFormat: @"%@-%@", [num substringToIndex:7], [num substringFromIndex:7]];
			}
		}
		return num;
	}
	else
	{
		return num;
	}
}

- (IBAction)switchView:(id)sender
{
    // Does nothing if row counter is 0
	if(rowCounter != 0)
	{
        // Check if button is being selected
		if(buttonSelect == true && columnCounter != 0)
		{
            // Stops timer and reset iteration counter
			[uniTimer invalidate];
			uniTimer = nil;
			iterationCounter = 0;
			
            // Special case for row 4
			if(rowCounter == 4)
			{
				switch (columnCounter)
				{
                    // Back space
					case 1:
						if([number length] == 1)
						{
							number = NULL;
						}
						else
						{
							number = [number substringToIndex:[number length] - 1];
							if([number hasSuffix:@"-"])
							{
								number = [number substringToIndex:[number length] - 1];
							}
						}
						reverseNumber.text = number;
						rowCounter= 0;
						columnCounter = 0;
						buttonSelect = false;
						[self rowChange];
						uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
						NSLog(@"%@",number);
						break;
                    // 0
					case 2:
                        [self appendNum:(9)];
                        rowCounter= 0;
						columnCounter = 0;
                        buttonSelect = false;
						[self rowChange];
						uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
						break;
                    // Clear
					case 3:
						number = nil;
						reverseNumber.text =  number;
						rowCounter= 0;
						columnCounter = 0;
						buttonSelect = false;
						[self rowChange];
						uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
						NSLog(@"%@",number);
						break;
				}
			}
            // Case for row 5
			else if(rowCounter == 5)
			{
				switch (columnCounter)
				{
                    // Search number
					case 1:
                    {

                        rowCounter= 0;
                        columnCounter = 0;
						buttonSelect = false;
                        // Pass number to ResultSearchDirectoryViewController and search
						if (number != nil)
						{
							DataStorage *data = [DataStorage sharedData];
							[data setReverseNumber:number];
							number = nil;
							reverseNumber.text = number;
							ResultSearchDirectoryViewController	*myViewController = [[ResultSearchDirectoryViewController alloc]
																	 initWithNibName:@"ResultSearchDirectoryView"
																	 bundle:nil];
							[self presentModalViewController:myViewController animated:NO]; 
							[number release];
							[highlightArea setImage:nil];
						}
                        // Brings up invalid input screen if number is nil
						else
						{
							InvalidInputViewController *myViewController = [[InvalidInputViewController alloc]
																		 initWithNibName:@"InvalidInputView"
																		 bundle:nil];
							[self presentModalViewController:myViewController animated:NO]; 
							;
							[highlightArea setImage:nil];
						}
							
						break;
                    }
                    // Back to main menu
					case 2:
                    {
                        rowCounter= 0;
                        columnCounter = 0;
						[self dismissModalViewControllerAnimated:NO];
						[number release];
						break;
                    }
				}
			}
            // Button select for number buttons
			else
			{
				NSLog(@"column:%d row:%d",columnCounter,rowCounter);
				[self appendNum:(columnCounter-1+(rowCounter-1)*3)];
				rowCounter= 0;
				columnCounter = 0;
				buttonSelect = false;
				[self rowChange];
				uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
			}
		}
        // Case for row select
		else
		{
			[uniTimer invalidate];
			uniTimer = nil;
			buttonSelect = true;
			columnCounter = 0;
			[self buttonChange];
			uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(buttonChange) userInfo:nil repeats:YES];
		}
	}
}

- (void)buttonChange 
{
    // Special reset case for row 5
	if (rowCounter == 5)
	{
		if (columnCounter == 2)
		{
				columnCounter = 0;
				iterationCounter += 1;
		}
	}
    // Generic reset case
	else
	{
		if (columnCounter == 3)
		{
				columnCounter = 0;
				iterationCounter += 1;
		}
	}
    // Timeout reset
	if(iterationCounter == 3)
	{
		[uniTimer invalidate];
		uniTimer = nil;
		iterationCounter = 0;
        columnCounter = 0;
		rowCounter= 0;
		buttonSelect = false;
		[self rowChange];
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
	
	}
    // Change highlighted button
	else
	{
		columnCounter += 1;
		NSString *next = highlightColor;
		if(rowCounter == 5)
        {
			next = [next stringByAppendingString:@"_search_"];
        }
		else
        {
			next = [next stringByAppendingString:@"_dialer_"];
        }

		next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", columnCounter+(rowCounter-1)*3]];
		next = [next stringByAppendingString:@".png"];
		[self highlightChange:next];
	}
		
}


- (void)rowChange 
{
	// Reset row counter
	if(rowCounter == 5)
	{
		rowCounter = 0;
	}
	rowCounter+= 1;
	NSString *next = highlightColor;
    next = [next stringByAppendingString:@"_dialer_row"];  
	next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", rowCounter]];
	next = [next stringByAppendingString:@".png"];
	[self highlightChange:next];
	
}

@end
